<template>
  <div>
    <el-form-item
      :rules="[{required: true, trigger: 'blur', validator: (rule, value, cb) => {
        if (authInfoForm.userType) {
          return cb()
        } else {
          return cb(error('请选择账号类型'))
        }
      }}]" label="账号类型" prop="userType"
    >
      <auth-user-type-select
        v-model="authInfoForm.userType"
        placeholder="请选择账号类型，注意：个人账号只能由使用人申请"
      />
    </el-form-item>
    <el-form-item
      v-if="authInfoForm.userType==='SYSTEM'" :rules="[{required: true, trigger: 'blur', validator: (rule, value, cb) => {
        if (authInfoForm.usernames&&authInfoForm.usernames.length!==0) {
          return cb()
        } else {
          return cb(error('请输入账号名称'))
        }
      }}]" label="账号名称"
      prop="usernames"
    >
      <string-format-mul-select
        v-model="authInfoForm.usernames"
        :filter-function="(val)=>{return val!==''}" :format-function="(val)=>{return val.trim()}"
        :allow-create="true" placeholder="请输入账号名称"
      />
    </el-form-item>
    <el-form-item
      v-if="authInfoForm.userType" :rules="[{required: true, trigger: 'blur', validator: (rule, value, cb) => {
        if (authInfoForm.useUserIds&&authInfoForm.useUserIds.length!==0) {
          return cb()
        } else {
          return cb(error('请选择使用人'))
        }
      }}]" label="使用人"
      prop="useUsers"
    >
      <user-id-multiple-select v-model="authInfoForm.useUserIds" placeholder="请选择使用人"/>
    </el-form-item>
    <el-form-item label="访问ip" prop="ips">
      <string-format-mul-select
        v-model="authInfoForm.ips" :filter-function="(val)=>{return val!==''}"
        :allow-create="true" :format-function="(val)=>{return val.trim()}" placeholder="请输入访问IP"
      />
    </el-form-item>
    <el-form-item
      :rules="[{required: true, trigger: 'blur', validator: (rule, value, cb) => {
        if (!authInfoForm.startTime) {
          return cb(error('请选择开始时间'))
        } else if (authInfoForm.endTime < authInfoForm.startTime) {
          return cb(error('结束时间必须大于开始时间'))
        } else if (!authInfoForm.userType) {
          return cb(error('请先选择账号类型'))
        } else if (authInfoForm.userType === 'UAP' && intervalTime(authInfoForm.startTime,authInfoForm.endTime)>90) {
          return cb(error('个人账号一次赋权时间不能超过90天'))
        } else {
          return cb()
        }
      }}]" label="开始时间" prop="startTime"
    >
      <el-date-picker v-model="authInfoForm.startTime" placeholder="请选择权限开始时间" type="date" :disabled=true />
    </el-form-item>
    <el-form-item
      :rules="[{
        required: true, trigger: 'blur', validator: (rule, value, cb) => {
          if (!authInfoForm.endTime) {
            return cb(error('请选择结束时间'))
          } else if (authInfoForm.endTime < authInfoForm.startTime) {
            return cb(error('结束时间必须大于开始时间'))
          } else if (!authInfoForm.userType) {
            return cb(error('请先选择账号类型'))
          } else if (authInfoForm.userType === 'UAP' && intervalTime(authInfoForm.startTime,authInfoForm.endTime)>90) {
            return cb(error('个人账号一次赋权时间不能超过90天'))
          } else {
            return cb()
          }
        }
      }]" label="结束时间" prop="endTime"
    >
      <el-date-picker v-model="authInfoForm.endTime" placeholder="请选择权限结束时间" type="date" clearable @input="$forceUpdate()" :disabled=isEndTimeDisabled() />
    </el-form-item>
    <el-form-item
      :rules="[{required: true, trigger: 'blur', validator: (rule, value, cb) => {
        if (authInfoForm.authType) {
          return cb()
        } else {
          return cb(error('请选择数据库类型'))
        }
      }}]" label="数据库类型"
      prop="authService"
    >
      <auth-service-select
        v-model="authInfoForm.authService" :mode="mode"
        placeholder="请选择数据库类型"
      />
    </el-form-item>
    <el-form-item
      v-if="authInfoForm.authService" :rules="[{required: true, trigger: 'blur', validator: (rule, value, cb) => {
        if (authInfoForm.authType) {
          return cb()
        } else {
          return cb(error('请输入访问权限'))
        }
      }}]" label="权限类型"
      prop="authType"
    >
      <auth-type-select v-model="authInfoForm.authType" :auth-service="authInfoForm.authService" :mode="mode"/>
      <div
        v-if="authInfoForm.authService==='HIVE'&authInfoForm.authType==='COLUMN'"
        style="margin-left: 150px; font-size: 10px; color: #409EFF"
      >
        {{ '添加hive数据权限将自动申请presto的对应表数据权限' }}
      </div>
    </el-form-item>
    <el-form-item
      v-if="authInfoForm.authType" :rules="[{
        required: true, trigger: 'blur', validator: (rule, value, cb) => {
          if (authInfoForm.accesses && authInfoForm.accesses.length > 0) {
            return cb()
          } else {
            return cb(error('请输入访问权限'))
          }
        }
      }]" label="访问权限"
      prop="accesses"
    >
      <auth-access-multiple-select
        v-model="authInfoForm.accesses" :auth-service="authInfoForm.authService" :auth-type="authInfoForm.authType"
        :mode="mode"
      />
    </el-form-item>
    <el-card
      v-for="(infoResource, index) in authInfoForm.authInfoResources" :key="index" class="box-card"
      style="margin-bottom: 20px"
    >
      <div slot="header">
        <span style="vertical-align: middle">
          申请资源{{ index + 1 }}
        </span>
        <span style="float: right; padding: 3px 0; vertical-align: middle">
          <el-button type="text" @click="addAuthInfo(index)">复制</el-button>
          <el-button
            v-if="authInfoForm.authInfoResources.length>1" type="text"
            @click="deleteAuthInfo(index)"
          >删除</el-button>
          <el-button
            v-if="authInfoForm.authInfoResources[index].show===false"
            type="text"
            @click="authInfoForm.authInfoResources[index].show=true"
          >展开</el-button>
          <el-button
            v-else type="text"
            @click="authInfoForm.authInfoResources[index].show=false"
          >收起</el-button>
        </span>
      </div>
      <apply-auth-info-resource-div
        v-show="authInfoForm.authInfoResources[index].show"
        v-model="authInfoForm.authInfoResources[index].resource"
        :auth-service="authInfoForm.authService"
        :auth-type="authInfoForm.authType"
        :mode="mode"
      />
    </el-card>
  </div>
</template>

<script>
import AuthServiceSelect from "@/views/auth/authServiceSelect";
import AuthTypeSelect from "@/views/auth/authTypeSelect";
import AuthAccessMultipleSelect from "@/views/auth/authAccessMultipleSelect";
import UserMultipleSelect from "@/views/system/user/userMultipleSelect";
import AuthUserTypeSelect from "@/views/auth/authUserTypeSelect";
import StringFormatMulSelect from "@/views/common/stringFormatMulSelect";
import ApplyAuthInfoResourceDiv from "@/views/auth/apply/applyAuthInfoResourceDiv";
import UserIdMultipleSelect from "@/views/system/user/userIdMultipleSelect.vue";

export default {
  name: "ApplyAuthInfoDiv",
  components: {
    UserIdMultipleSelect,
    ApplyAuthInfoResourceDiv,
    StringFormatMulSelect,
    AuthUserTypeSelect,
    UserMultipleSelect,
    AuthAccessMultipleSelect,
    AuthTypeSelect,
    AuthServiceSelect,
  },
  props: {
    mode: {type: String, default: null},
    value: {
      type: Object, default: function () {
        return {}
      }
    },
  },
  data() {
    return {
      authInfoForm: {
        authService: null,
        authType: null,
        authInfoResources: [this.resetResources()],
      },
      useUsersDisabled: false,
      usernamesDisabled: false,
    }
  },
  watch: {
    'value': {
      handler(val) {
        this.authInfoForm = val
      }, immediate: true
    },

    'authInfoForm': {
      handler(val) {
        this.$emit('input', val)
      }, immediate: false
    },

    'authInfoForm.userType': {
      handler(val) {
        if (val === 'UAP') {
          this.authInfoForm.usernames = [sessionStorage.getItem('bdpUserSn')]
          if (this.mode === "QUICK"){
            this.authInfoForm.endTime = new Date().setDate(new Date().getDate() + 90)
          }
          this.useUsersDisabled = true
          this.usernamesDisabled = true
        } else {
          this.authInfoForm.usernames = []
          if (this.mode === "QUICK"){
            this.authInfoForm.endTime = new Date().setFullYear(new Date().getFullYear() + 30)
          }
          this.useUsersDisabled = false
          this.usernamesDisabled = false
        }
        this.authInfoForm.useUserIds = [sessionStorage.getItem('bdpUserId')]
      }, immediate: false
    },

    'authInfoForm.authService': {
      handler() {
        this.authInfoForm.authType = null
      }, immediate: false
    },

    'authInfoForm.authType': {
      handler(val) {
        this.authInfoForm.accesses = []
        if (val) {
          this.authInfoForm.authInfoResources = [this.resetResources()]
        } else {
          this.authInfoForm.authInfoResources = []
        }
      }, immediate: false
    },
  },
  methods: {
    resetResources() {
      return {show: true, resource: {}}
    },

    addAuthInfo(index) {
      let copies = JSON.parse(JSON.stringify(this.authInfoForm.authInfoResources))
      this.$set(this.authInfoForm, 'authInfoResources', [])
      this.$nextTick(() => {
        copies.splice(index, 0, JSON.parse(JSON.stringify(copies[index])))
        this.$set(this.authInfoForm, 'authInfoResources', copies)
      })
    },

    deleteAuthInfo(index) {
      let copies = JSON.parse(JSON.stringify(this.authInfoForm.authInfoResources))
      this.$set(this.authInfoForm, 'authInfoResources', [])
      this.$nextTick(() => {
        copies.splice(index, 1)
        this.$set(this.authInfoForm, 'authInfoResources', copies)
      })
    },

    intervalTime(startDate, endDate) {
      let startTime = Date.parse(startDate)
      let endTime = Date.parse(endDate)
      return (endTime - startTime) / 1000 / 3600 / 24
    },

    error(msg) {
      return new Error(msg)
    },

    // 根据 mode 的值来判断是否禁用日期选择器
    isEndTimeDisabled() {
      return this.mode === "QUICK";
    }
  }
}
</script>

<style scoped>

</style>
